const { listToMatrix, always } = require('../../lib/util.js');
const qiniuUploader = require("../../lib/qiniuUploader");
var app = getApp();
var index = 1;
Page({
  data: {
    //相册guid
    AlbumGuid: '',
    // 相册列表数据
    albumList: [],
    hasMore: true,
    // 是否显示loading
    showLoading: false,
    // loading提示语
    loadingMessage: '',
    // 是否显示toast
    showToast: false,
    // 提示消息
    toastMessage: '',
    // 是否显示动作命令
    showActionsSheet: false,
  },
  // 显示loading提示
  showLoading(loadingMessage) {
    this.setData({ showLoading: true, loadingMessage });
  },

  // 隐藏loading提示
  hideLoading() {
    this.setData({ showLoading: false, loadingMessage: '' });
  },

  // 显示toast消息
  showToast(toastMessage) {
    this.setData({ showToast: true, toastMessage });
  },

  // 隐藏toast消息
  hideToast() {
    this.setData({ showToast: false, toastMessage: '' });
  },

  // 隐藏动作列表
  hideActionSheet() {
    this.setData({ showActionsSheet: false, imageInAction: '' });
  },
  onLoad: function (options) {
    console.log(options);
    this.setData({
      AlbumGuid: options.AlbumGuid,
      albumList: [],
    })
    this.showLoading('加载中...');
    this.loadImages();
  },
  loadImages: function () {
    var that = this
    wx.request({
      url: app.globalData.ServiceUrl + 'file/getAttachByAlbumGuid', //接口地址
      method: 'POST',
      data: {
        ValidateData: app.globalData.ValidateData,
        paras: {
          AlbumGuid: that.data.AlbumGuid,
          index: index,
          currentPageCount: '10'
        }
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data.UserArea.list.length == 0) {
          that.setData({
            hasMore: false,
          })
        } else {
          that.setData({
            albumList: that.data.albumList.concat(res.data.UserArea.list),
          })
        }
        wx.stopPullDownRefresh();
        that.hideLoading();
        index++;
        typeof cb == 'function' && cb(res.data)
      }
    })
  },
  // 从相册选择照片或拍摄照片
  chooseImage() {
    console.log("上传图片");
    var that = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#155D3E",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage('album')
          } else if (res.tapIndex == 1) {
            that.chooseWxImage('camera')
          }
        }
      }
    })
  },
  chooseWxImage: function (type) {
    var that = this;
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      success: function (res) {
        console.log(res.tempFilePaths);
        var tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths)
        that.setData({
          albumList_url: [],
        });
        that.showLoading('上传中...');
        var imgList = [];//多张图片地址，保存到一个数组当中
        var state = 0;//state记录当前已经上传到第几张图片
        new Promise(function (resolve, reject) {
          for (var i = 0; i < tempFilePaths.length; i++) {
            qiniuUploader.upload(tempFilePaths[i], (res) => {
              state++;
              console.log(state)
              imgList.push(res.imageURL);
              var arr = res.key.split('.');
              var OPEN_ID_ = wx.getStorageSync('OPEN_ID');
              wx.request({
                url: app.globalData.ServiceUrl + 'file/SaveAttach',
                method: 'POST',
                data: {
                  ValidateData: app.globalData.ValidateData,
                  paras: {
                    AttachName: res.key,
                    AttachLength: '',
                    AttachUrl: res.imageURL,
                    OwnerUserGuid: OPEN_ID_,
                    AlbumGuid: that.data.AlbumGuid,
                    AttachType: arr[arr.length - 1]
                  }
                },
                header: {
                  'content-type': 'application/json' // 默认值
                },
                success: function (res) {
                  console.log(tempFilePaths.length+"kkkkkkkkk")
                },
                fail: function (res) {
                  console.log(res)
                }
              })
              if (state == tempFilePaths.length) {
                resolve(imgList);
              }
            }, (error) => {
              reject('error');
              console.log('error: ' + error);
            }, {
                region: app.globalData.region,
                uploadURL: app.globalData.uploadURL,
                domain: app.globalData.domain,
                uptokenURL: app.globalData.uptokenURL,
              })
          }
        }).then(function (imgList) {
          index = 1;
          that.setData({
            scrollTop: 0,
            albumList: []
          });
          that.loadImages();
        })
      }
    })
  },
  // 进入预览模式
  enterPreviewMode(e) {
    this.data.pictures = [],
      console.log(this.data.albumList)
    var current = e.target.dataset.src;
    console.log(e)
    for (let i = 0; i < this.data.albumList.length; i++) {
      this.data.pictures.push(this.data.albumList[i].AttachUrl);
    }
    wx.previewImage({
      current: current.AttachUrl, // 当前显示图片的http链接  
      urls: this.data.pictures, // 需要预览的图片http链接列表  
    })
  },
  // 显示可操作命令
  showActions(event) {
    this.setData({ showActionsSheet: true, imageInAction: event.target.dataset.src });
  },
  // 删除图片
  deleteImage() {
    let that = this;
    let item = this.data.imageInAction;
    console.log(item)
    this.setData({ showActionsSheet: false, imageInAction: '' });
    var OPEN_ID_ = wx.getStorageSync('OPEN_ID');
    wx.request({
      url: app.globalData.ServiceUrl + 'file/DeleteAttach', //接口地址
      method: 'POST',
      data: {
        ValidateData: app.globalData.ValidateData,
        paras: {
          AttachGuids: item.AttachGuid,
          OwnerUserGuid: OPEN_ID_
        }
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res.data)
        if (res.data.BusinessInfo.Code == 1 && res.data.ReturnInfo.Code == 1) {
          // 从图片列表中移除
          let albumList = that.data.albumList;
          let index = 0;
          for (var i = 0; i < albumList.length; i++) {
            if (albumList[i].AttachGuid == item.AttachGuid) {
              index = i;
            }
          }
          albumList.splice(index, 1);
          that.setData({ albumList });
          // that.showToast(res.data.BusinessInfo.Description);
        } else {
          that.showToast(res.data.BusinessInfo.Description);
        }
      }
    })
  },
  onPullDownRefresh: function () {
    var that = this
    that.setData({
      albumList: [],
      hasMore: true,
      showLoading: true,
    })
    index = 1;
    this.loadImages();
  },
  onReachBottom: function () {
    var that = this
    if (!that.data.showLoading) {
      that.loadImages();
    }
  },
  onShareAppMessage: function (res) {
    return {
      title: '来看看我的照片',
      path: 'pages/album/album?AlbumGuid=' + this.data.AlbumGuid,
      imageUrl: 'https://image.chenjianfeng.xyz/20180904140847.png',
    }
  }
})